package com.touzhijia.authority.security;

import com.touzhijia.authority.domain.entity.User;
import lombok.ToString;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * 自定义 用户信息
 * <p>
 * 作者： lzw<br/>
 * 创建时间：2018-03-16 17:41 <br/>
 */
@ToString(exclude = {"authorities", "user"})
public class CustomUserDetails implements UserDetails, CredentialsContainer {

    private final String username;
    private String password;
    private final boolean accountNonExpired;
    private final boolean accountNonLocked;
    private final boolean credentialsNonExpired;
    private final boolean enabled;

    private User user;
    private final Set<CustomGrantedAuthority> authorities;

    public CustomUserDetails(User user) {
        this.username = user.getUsername();
        this.password = user.getPassword();
        this.accountNonExpired = !Objects.equals(User.User_Type_1, user.getUserType()) || Objects.equals(user.getLdapExist(), User.Ldap_Exist_1);
        this.accountNonLocked = Objects.equals(user.getLocked(), User.Locked_0);
        this.credentialsNonExpired = true;
        this.enabled = Objects.equals(user.getEnabled(), User.Enabled_1);
        this.user = user;
        this.authorities = new HashSet<>();
    }

    public User getUser() {
        return user;
    }

    @Override
    public void eraseCredentials() {
        this.password = "";
        user.setPassword("");
    }

    @Override
    public Collection<CustomGrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}
